<!-- src/views/DefectDetail.vue -->
<template>
  <a-card title="缺陷详情" :bordered="false">
    <a-row :gutter="24">
      <!-- 图像展示区域 -->
      <a-col :span="16">
        <div class="image-container">
          <img :src="formattedImage" class="detection-image"/>
          <canvas ref="canvasRef" class="overlay-canvas" />
        </div>
      </a-col>

      <!-- 结果详情 -->
      <a-col :span="8">
        <a-card title="缺陷信息" class="result-details">
          <a-spin :spinning="loading">
            <a-divider />

            <div class="summary-section">
              <a-descriptions  :column="1">
                <a-descriptions-item label="记录ID">
                  {{ recordId }}
                </a-descriptions-item>
                <a-descriptions-item label="检测时间">
                  {{ detectionTime }}
                </a-descriptions-item>
                <a-descriptions-item label="缺陷种数">
                  {{ defects.length }}
                </a-descriptions-item>
                <a-descriptions-item v-if="defectTypeNames.length>0" label="缺陷类型" style="">
                  <a-tag v-for="(item, index) in defectTypeNames"
                         :key="index"
                         :color="getTagColor(item)">
                    {{ item }}
                  </a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="综合判定">
                  <a-tag :color="defects.length ? 'red' : 'green'">
                    {{ defects.length ? '不合格' : '合格' }}
                  </a-tag>
                </a-descriptions-item>
              </a-descriptions>
            </div>
            <a-button type="primary" @click="goBack" style="margin-top: 20px;position: absolute;right: 0">返回</a-button>
          </a-spin>
        </a-card>
      </a-col>
    </a-row>
  </a-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { queryidUsingGet } from '@/api/detectionRecordController.ts'

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const currentImage = ref('');
const canvasRef = ref(null);
const defects = ref([]);
const detectionTime = ref('');
const recordId = ref(null);
const defectTypeNames = ref('')
// 从路由获取 id
const id = route.params.id;



const goBack = () => {
  router.go(-1);
};

// 格式化 base64 图片
const formattedImage = computed(() => {
  if (!currentImage.value) return '';
  // 如果已经是完整 base64 URL，直接返回
  if (currentImage.value.startsWith('data:image')) {
    return currentImage.value;
  }
  // 添加前缀，假设是 JPEG 格式
  return `data:image/jpeg;base64,${currentImage.value}`;
});

const fetchDefectDetail = async () => {
  try {
    loading.value = true;
    const response = await queryidUsingGet({ id });
    const data = response.data[0];
    console.log(data)
    if (data) {
      recordId.value = data.id;
      currentImage.value = data.image;
      detectionTime.value = new Date(data.detectionTime).toLocaleString(); // 格式化时间
      defectTypeNames.value = data.defectTypeNames;
      // 构造 defects 数组，后端未提供置信度和位置，暂时设为未知
      defects.value = data.defectTypeNames.map(type => ({
        type,
        confidence: null, // 后端未提供，设为 null
        position: null // 后端未提供，设为 null
      }));
    } else {
      message.warning('未找到该记录的详情');
    }
  } catch (error) {
    message.error('获取缺陷详情失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const getTagColor = (type) => {
  const colors = {
    '划痕': 'yellow',
    '夹杂物': 'purple',
    '斑点': 'cyan', // 对应 Patches
    '裂纹': 'orange',
    '麻面': 'blue', // 对应 Pitted Surface
    '轧入氧化皮': 'gray' // 对应 Rolled-in Scale
  };
  return colors[type] || 'blue';
};

const zoomToDefect = (position) => {
  if (!position) {
    message.info('该缺陷无位置信息');
    return;
  }
  // 定位逻辑（如果后端提供位置信息，可以在这里实现）
  console.log('Zoom to:', position);
};



onMounted(() => {
  fetchDefectDetail();
});
</script>

<style scoped>
.image-container {
  position: relative;
  width: 100%;
  height: 600px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
}

.detection-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.overlay-canvas {
  position: absolute;
  top: 0;
  left: 0;
  pointer-events: none;
}

.result-details {
  height: 600px;
  overflow-y: auto;
}

.summary-section {
  margin-top: 16px;
  padding: 12px;
  background: #fafafa;
  border-radius: 8px;
}
</style>
